﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Transactions;
using System.Web;
using qlqa.Models.Form.HoaDonForm;
using qlqa.Models.LinQ;

namespace qlqa.Delegate.HoaDonDelegate
{
    public class HoaDonDelegate
    {
        readonly DatabaseDataContext _database = new DatabaseDataContext();
        
        readonly int _userId = Convert.ToInt32(HttpContext.Current.Session["USERID"]??0);

        public bool KiemTraBanHienDangCoHoaDon(int? idBan)
        {
            try
            {
                if (idBan == null) return false;

                var list = _database.tb_HoaDons.Where(
                    p =>
                        p.IdBan == idBan && (p.IsThanhToan == false || p.IsThanhToan == null) && (p.IsDelete == false ||
                        p.IsDelete == null)).ToList();
                if (list.Count > 0)
                {
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public tb_HoaDon CreateHoaDon(int? id)
        {
            try
            {
                if (id == null) return null;

                var hoaDon = new tb_HoaDon
                {
                    IdBan = Convert.ToInt32(id),
                    ThanhTien = 0,
                    IsThanhToan = false,
                    IsDelete = false,
                    NgayTao = DateTime.Now,
                    NguoiTao = _userId
                };
                _database.tb_HoaDons.InsertOnSubmit(hoaDon);
                _database.SubmitChanges();
                return hoaDon;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public tb_ChiTietHoaDon CreateChiTietHoaDon(long idHoaDon, int idBan, int idMon, int soluong)
        {
            try
            {
                var hoaDon = _database.tb_HoaDons.Where(p =>
                    (p.IsDelete == null || p.IsDelete == false) && (p.IsThanhToan == null || p.IsThanhToan == false))
                    .FirstOrDefault(p => p.Id == idHoaDon && p.IdBan == idBan);
                var monAn = _database.tb_MonAns.FirstOrDefault(p => p.Id == idMon);
                if (hoaDon != null && monAn != null)
                {
                    var chiTietHoaDon = new tb_ChiTietHoaDon
                    {
                        IdHoaDon = hoaDon.Id,
                        IdBan = hoaDon.IdBan,
                        Gia = monAn.Gia,
                        GiaThuc = monAn.Gia,
                        IdMon = monAn.Id,
                        SoLuong = soluong,
                        NgayTao = DateTime.Now,
                        NguoiTao = _userId
                    };
                    chiTietHoaDon.NgayTao = chiTietHoaDon.NgaySua = DateTime.Now;
                    _database.tb_ChiTietHoaDons.InsertOnSubmit(chiTietHoaDon);
                    _database.SubmitChanges();
                    return chiTietHoaDon;
                }

                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public tb_ChiTietHoaDon UpdateChiTietHoaDon(long idHoaDon, long idChiTietHoaDon, long gia, int soluong)
        {
            try
            {
                var chiTietHoaDon = _database.tb_ChiTietHoaDons.FirstOrDefault(p => p.Id == idChiTietHoaDon && p.IdHoaDon == idHoaDon);
                if (chiTietHoaDon != null)
                {
                    chiTietHoaDon.GiaThuc = gia;
                    chiTietHoaDon.SoLuong = soluong;
                    chiTietHoaDon.NgaySua = DateTime.Now;
                    chiTietHoaDon.NguoiSua = _userId;
                    _database.SubmitChanges();
                    return chiTietHoaDon;
                }

                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public tb_HoaDon GetHoaDonTheoBan(int? idBan)
        {
            try
            {
                var hoaDon = _database.tb_HoaDons.Where(
                    p =>
                        p.IdBan == idBan && (p.IsThanhToan == false || p.IsThanhToan == null) && (p.IsDelete == false ||
                        p.IsDelete == null)).OrderByDescending(p=>p.Id).FirstOrDefault();
                if (hoaDon != null)
                {
                    UpdateHoaDonThanhTien(hoaDon.Id);
                    return hoaDon;
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public tb_HoaDon GetHoaDon(long? idHoaDon)
        {
            try
            {
                var hoaDon = _database.tb_HoaDons.Where(
                    p =>
                        p.Id == idHoaDon && (p.IsDelete == false ||
                        p.IsDelete == null)).OrderByDescending(p => p.Id).FirstOrDefault();
                if (hoaDon != null)
                {
                    UpdateHoaDonThanhTien(hoaDon.Id);
                    return hoaDon;
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public List<tb_HoaDon> GetDanhSachHoaDon()
        {
            try
            {
                var list = _database.tb_HoaDons.Where(p => (p.IsDelete == null || p.IsDelete == false)).OrderByDescending(p=>p.Id).ToList();
                return list;
            }
            catch (Exception)
            {
                return new List<tb_HoaDon>();
            }
        }

        public List<tb_ChiTietHoaDon> GetChiTietHoaDonTheoHoaDon(long id)
        {
            try
            {
                var list = _database.tb_ChiTietHoaDons.Where(p => p.IdHoaDon == id).ToList();
                return list;
            }
            catch (Exception)
            {
                return new List<tb_ChiTietHoaDon>();
            }
        }

        public tb_ChiTietHoaDon GetChiTietHoaDon(long idChiTiet)
        {
            try
            {
                var chiTietHoaDon = _database.tb_ChiTietHoaDons.FirstOrDefault(p => p.Id == idChiTiet);
                return chiTietHoaDon;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public bool UpdateHoaDonThanhTien(long idHoaDon)
        {
            try
            {
                var hoaDon =
                    _database.tb_HoaDons.FirstOrDefault(
                        p =>
                            p.Id == idHoaDon && (p.IsDelete == false || p.IsDelete == null) &&
                            (p.IsThanhToan == false || p.IsThanhToan == null));
                if (hoaDon != null)
                {
                    var list = _database.tb_ChiTietHoaDons.Where(p => p.IdHoaDon == hoaDon.Id).ToList();
                    if (list.Any())
                    {
                        long thanhTien = 0;
                        foreach (var item in list)
                        {
                            var gia = 0;
                            var soluong = 0;
                            if (item.GiaThuc != null && item.GiaThuc > 0)
                                gia = Convert.ToInt32(item.GiaThuc);
                            else
                            {
                                var mon = _database.tb_MonAns.FirstOrDefault(p => p.Id == item.IdMon);
                                if (mon != null)
                                {
                                    gia = Convert.ToInt32(item.Gia);
                                }
                            }
                            
                            if (item.SoLuong != null && item.SoLuong > 0)
                            {
                                soluong = (int) item.SoLuong;
                            }
                            var x = gia * soluong;
                            thanhTien += x;
                        }

                        hoaDon.ThanhTien = thanhTien;
                        hoaDon.NgaySua = DateTime.Now;
                        hoaDon.NguoiSua = _userId;
                        _database.SubmitChanges();
                    }
                    else
                    {
                        hoaDon.ThanhTien = 0;
                        _database.SubmitChanges();
                    }
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool HuyHoaDon(long? idHoaDon)
        {
            try
            {
                var hoaDon = _database.tb_HoaDons.Where(p=>p.IsDelete == false || p.IsDelete == null).FirstOrDefault(p => p.Id == idHoaDon);
                using (var tran = new TransactionScope())
                {
                    if (hoaDon != null)
                    {
                        var list = _database.tb_ChiTietHoaDons.Where(p => hoaDon != null && p.IdHoaDon == hoaDon.Id).ToList();
                        if (list.Any())
                        {
                            return false;
                        }

                        if (!string.IsNullOrEmpty(hoaDon.ArrayBan))
                        {
                            var array = hoaDon.ArrayBan.Split(',');
                            if (array.Any())
                            {
                                foreach (var s in array)
                                {
                                    int num1;
                                    var res = int.TryParse(s, out num1);
                                    if (res)
                                    {
                                        var ban = _database.tb_Bans.FirstOrDefault(p => p.Id == num1);
                                        if (ban != null)
                                        {
                                            ban.IdBan = 0;
                                            ban.TrangThaiSuDung = 1;
                                        }
                                    }
                                }
                            }
                        }

                        _database.tb_HoaDons.DeleteOnSubmit(hoaDon);
                    }
                    else
                    {
                        return false;
                    }
                    _database.SubmitChanges();
                    tran.Complete();
                    tran.Dispose();
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool XoaMonTrongChiTietHoaDon(long idChiTiet)
        {
            try
            {
                var chiTiet = _database.tb_ChiTietHoaDons.FirstOrDefault(p => p.Id == idChiTiet);
                if (chiTiet != null)
                {
                    _database.tb_ChiTietHoaDons.DeleteOnSubmit(chiTiet);
                    _database.SubmitChanges();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool UpdateOrderd(long id, long gia, int soluong)
        {
            try
            {
                using (var tran = new TransactionScope())
                {
                    var chiTiet = _database.tb_ChiTietHoaDons.FirstOrDefault(p => p.Id == id);
                    if (chiTiet != null)
                    {
                        chiTiet.GiaThuc = gia;
                        chiTiet.SoLuong = soluong;
                        chiTiet.NgaySua = DateTime.Now;
                        chiTiet.NguoiSua = _userId;
                        _database.SubmitChanges();
                        //Cập nhật thành tiền trong hóa đơn
                        UpdateHoaDonThanhTien(Convert.ToInt64(chiTiet.IdHoaDon));
                        tran.Complete();
                        tran.Dispose();
                        return true;
                    }
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool UpdateArrayBan(tb_HoaDon hoaDon)
        {
            try
            {
                var obj = _database.tb_HoaDons.FirstOrDefault(p => p.Id == hoaDon.Id);
                if (obj != null)
                {
                    obj.ArrayBan = hoaDon.ArrayBan;
                    obj.NguoiSua = _userId;
                    obj.NgaySua = DateTime.Now;
                }
                _database.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool TinhTienHoaDon(long? idHoaDon)
        {
            try
            {
                var hoaDon = _database.tb_HoaDons.FirstOrDefault(p => p.Id == idHoaDon && (p.IsDelete == null || p.IsDelete == false));
                if (hoaDon != null)
                {
                    hoaDon.IsThanhToan = true;
                    var date = DateTime.Now;
                    hoaDon.Ngay = date.Day;
                    hoaDon.Thang = date.Month;
                    hoaDon.Nam = date.Year;
                    hoaDon.NgayTao = date;
                    hoaDon.NguoiTao = _userId;

                    var ban = _database.tb_Bans.FirstOrDefault(p => p.Id == hoaDon.IdBan);
                    if (ban != null)
                    {
                        var list = GetMergeTables(ban.Id);
                        if(list.Any())
                            foreach (var item in list)
                            {
                                item.IdBan = 0;
                                item.TrangThaiSuDung = 1;
                            }
                        ban.TrangThaiSuDung = 1;

                        _database.SubmitChanges();
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public List<tb_Ban> GetMergeTables(int idBanChinh)
        {
            try
            {
                var hoaDon = _database.tb_HoaDons.Where(
                    p =>
                        p.IdBan == idBanChinh && (p.IsThanhToan == false || p.IsThanhToan == null) && (p.IsDelete == false ||
                        p.IsDelete == null)).OrderByDescending(p => p.Id).FirstOrDefault();

                if (hoaDon == null) return new List<tb_Ban>();

                if (string.IsNullOrEmpty(hoaDon.ArrayBan)) return new List<tb_Ban>();

                var list = new List<tb_Ban>();

                var array = hoaDon.ArrayBan.Split(',');
                if (!array.Any()) return list;
                foreach (var s in array)
                {
                    int num1;
                    var res = int.TryParse(s, out num1);
                    if (!res) continue;
                    var ban = _database.tb_Bans.FirstOrDefault(p => p.Id == num1);
                    if (ban != null)
                    {
                        list.Add(ban);
                    }
                }

                return list;
            }
            catch (Exception)
            {
                return new List<tb_Ban>();
            }
        }

        public List<tb_HoaDon> LocHoaDon(HoaDonForm input)
        {
            try
            {
                List<tb_HoaDon> list;

                if (input.ThuTuUuTien == 1)
                {
                    list = _database.tb_HoaDons.Where(p => (p.IsDelete == null || p.IsDelete == false)).OrderByDescending(p => p.ThanhTien).ToList();
                }
                else if (input.ThuTuUuTien == 2)
                {
                    list = _database.tb_HoaDons.Where(p => (p.IsDelete == null || p.IsDelete == false)).OrderBy(p => p.ThanhTien).ToList();
                }
                else
                {
                    list = _database.tb_HoaDons.Where(p => (p.IsDelete == null || p.IsDelete == false)).ToList();
                }

                if (input.Nam != 0)
                {
                    if (input.Thang != 0)
                    {
                        list = list.Where(p => p.Nam == input.Nam && p.Thang == input.Thang).ToList();
                    }
                    list = list.Where(p => p.NgayTao != null && (p.Nam == input.Nam || p.NgayTao.Value.Year == input.Nam)).ToList();

                    return list;
                }
                else
                {
                    if (input.Thang != 0)
                    {
                        list = list.Where(p => p.NgayTao != null && (p.Thang == input.Thang || p.NgayTao.Value.Month == input.Thang)).ToList();
                        return list;
                    }

                    if (!string.IsNullOrEmpty(input.TuNgay) && !string.IsNullOrEmpty(input.DenNgay))
                    {
                        var from = ConvertToDateTime(input.TuNgay);
                        var to = ConvertToDateTime(input.DenNgay);
                        if (from != null && to != null)
                        {
                            list = list.Where(p => p.NgayTao != null && (p.NgayTao.Value.Date > from.Value.Date && p.NgayTao.Value.Date < to.Value.Date)).ToList();
                            return list;
                        }
                    }

                    if (!string.IsNullOrEmpty(input.NgayHoaDon))
                    {
                        var date = ConvertToDateTime(input.NgayHoaDon);

                        if (date != null)
                        {
                            list = list.Where(p => p.NgayTao != null && p.NgayTao.Value.Day == date.Value.Day && p.NgayTao.Value.Month == date.Value.Month && p.NgayTao.Value.Year == date.Value.Year).ToList();
                            return list;
                        }
                    }
                }

                return list;
            }
            catch (Exception)
            {
                return new List<tb_HoaDon>();
            }
        }

        public DateTime? ConvertToDateTime(string strDate) // strDate=dd/mm/yyyy
        {
            string[] arr = strDate.Split('/');
            if (arr.Length != 3)
                return null;
            string converdate = arr[2] + "-" + arr[1] + "-" + arr[0];
            return DateTime.Parse(converdate);
        }
    }
}